package game.server;

import game.Player;
import game.client.Table;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

import server.utils.PlayerWatcher;


public class ServerTable extends Table {
	private static final long serialVersionUID = 2761944248731766499L;
	protected ArrayList<Player> players;
	protected ArrayList<Player> waitlist;
	protected Game game;
	private Object lock;
	/**
	 * Creates new servertable with desired players.
	 * @param players behind the table.
	 */
	public ServerTable(Game game) {
		super();
		lock = new Object();
		this.game = game;
		waitlist = new ArrayList<Player>();
		players = new ArrayList<Player>();
	}
	/**
	 * Get all playing players.
	 * @return All playing players.
	 */
	public ArrayList<Player> getPlayingPlayers() {
		synchronized (lock) {
			return this.players;
		}
	}
	/**
	 * Get ArrayList of all the players in the game(players + waitList).
	 * @return the players
	 */
	public ArrayList<Player> getPlayers() {
		synchronized (lock) {
			ArrayList<Player> output = new ArrayList<Player>();
			output.addAll(players);
			output.addAll(waitlist);
			return output;
		}
	}
	/**
	 * Fold player.
	 * @param name Player to fold
	 */
	public void foldPlayer(String name) {
		synchronized (lock) {
			for (Player p : players) {
				if (p.getName().equalsIgnoreCase(name)) {
					players.remove(p);
					waitlist.add(p);
					break;
				}
			}
			
		}
	}
	/**
	 * Add all players waiting in waitlist to table's player array.
	 */
	public void emptyWaitlistBuffer() {
		synchronized (lock) {
			for (Player p : waitlist) {
				players.add(p);
			}
			waitlist.removeAll(waitlist);
			if (waitlist.size() > 0) {
				game.setRunning(true);
			}
		}
	}
	/**
	 * Method for adding a player to waitlist.
	 * @param player to add
	 */
	public void addPlayerToWaitlist(Player player) {
		synchronized (lock) {
			waitlist.add(player);
		}
	}
	/**
	 * Remove player from table.
	 * @param player to remove
	 */
	public void removePlayer(Player player) {
		synchronized (lock) {
			players.remove(player);
			waitlist.remove(player);
		}
	}
	/**
	 * Get nr of all the players in the game.
	 * @return Nr of all the players in the game
	 */
	public int getAllPlayersCount() {
		synchronized (lock) {
			return (players.size() + waitlist.size());
		}
	}
	/**
	 * Get currently in the game's players count
	 * @return nr of players in game(excluding folded and waiting players)
	 */
	public int getPlayersCount() {
		synchronized (lock) {
			return players.size();
		}
	}
	/**
	 * Get players array iterator. Must be synchronized outside!
	 * @return iterator of players arraylist
	 */
	public Iterator<Player> playersIterator() {
		return players.iterator();
	}

}
